
#include "removeDispose.h"


// 递归删除目录
void remove_dir(const char* real_path) {
    DIR* dir = opendir(real_path);
    if (!dir) {
        perror("opendir");
        return;
    }

    struct dirent* entry;
    struct stat statbuf;
    char sub_path[1024] = {0};
    while ((entry = readdir(dir)) != NULL) {
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }
        snprintf(sub_path, sizeof(sub_path), "%s/%s", real_path, entry->d_name);
        if (stat(sub_path, &statbuf) == -1) {
            perror("stat");
            continue;
        }
        if (S_ISDIR(statbuf.st_mode)) {
            remove_dir(sub_path);
        } else {
            if (unlink(sub_path) == -1) {
                perror("unlink file");
            }
        }
    }
    closedir(dir);
    if (rmdir(real_path) == -1) {
        perror("rmdir");
    }
}

// 物理删除文件/文件夹（数据库和磁盘，检测MD5是否最后一个）
void removet(int netfd, MYSQL* sql, char* username, char* path, char* real_path) {
    printf("COME IN REMOVE");
    char query[1024] = {0};
    MYSQL_RES* result;
    MYSQL_ROW row;

    // 1. 验证文件/文件夹存在且用户有权限
    sprintf(query,
             "SELECT id, type, md5 FROM user_file_table WHERE username = '%s' AND path = '%s'",
             username, path);
    if (mysql_query(sql, query)) {
        const char* err_msg = "数据库查询错误";
        send(netfd, err_msg, strlen(err_msg), 0);
        return;
    }
    printf("user is right");

    result = mysql_store_result(sql);
    if (!result) {
        const char* err_msg = "存储查询结果失败";
        send(netfd, err_msg, strlen(err_msg), 0);
        return;
    }

    
    if (mysql_num_rows(result) == 0) {
        const char* err_msg = "文件/文件夹不存在或无权限";
        send(netfd, err_msg, strlen(err_msg), 0);
        mysql_free_result(result);
        return;
    }

    row = mysql_fetch_row(result);
    char* file_md5 = row[6];
    mysql_free_result(result);

    // 构建实际要删除的路径
    char full_real_path[1024] = {0};
    sprintf(full_real_path, "%s/%s", real_path, file_md5);
    printf("path is right");
    
    bzero(query,sizeof(query));
    // 2. 物理删除数据库记录
    sprintf(query,
             "DELETE FROM user_file_table WHERE username = '%s' AND path = '%s'",
             username, path);
    if (mysql_query(sql, query)) {
        const char* err_msg = "数据库删除记录失败";
        send(netfd, err_msg, strlen(err_msg), 0);
        return;
    }
    
    // 3. 处理磁盘删除（文件需检测MD5）
    bzero(query,sizeof(query));
    if (strcmp(row[5],"f") == 0) {  // 文件
        sprintf(query,
                 "SELECT COUNT(*) FROM user_file_table WHERE md5 = '%s' AND username = '%s'",
                 file_md5, username);
        if (mysql_query(sql, query)) {
            const char* err_msg = "查询MD5计数失败";
            send(netfd, err_msg, strlen(err_msg), 0);
            return;
        }

        result = mysql_store_result(sql);
        if (!result) {
            const char* err_msg = "存储MD5计数结果失败";
            send(netfd, err_msg, strlen(err_msg), 0);
            return;
        }

        row = mysql_fetch_row(result);
        int md5_count = 1;
        mysql_free_result(result);

        if (md5_count <= 1) {  // 最后一个使用该MD5的文件，删除磁盘文件
            if (unlink(full_real_path) == -1) {
                const char* err_msg = "删除磁盘文件失败";
                send(netfd, err_msg, strlen(err_msg), 0);
                return;
            }
            printf("shan");
        }
    } else {  // 文件夹，直接删除
        struct stat statbuf;
        if (stat(full_real_path, &statbuf) == -1) {
            const char* err_msg = "获取文件夹状态失败";
            send(netfd, err_msg, strlen(err_msg), 0);
            return;
        }
        if (S_ISDIR(statbuf.st_mode)) {
            remove_dir(full_real_path);
        }
    }

    // 4. 反馈成功结果
    const char* success_msg = "删除操作完成";
    send(netfd, success_msg, strlen(success_msg), 0);
}



